# utils/tag_loader.py
from sqlalchemy.orm import Session
from models.comment_schema import TagDict
import logging

def load_label_rules_from_db(session: Session) -> dict:
    """
    从数据库加载标签规则，格式：
    {
        "外观设计": ["时尚外观", "颜色搭配", "车身造型"],
        "智能驾驶": ["自动驾驶", "泊车辅助", "雷达系统"],
        ...
    }
    """
    try:
        tags = session.query(TagDict).order_by(TagDict.id).all()
        label_rules = {}

        # 构建父标签
        for tag in tags:
            if tag.level == 1:
                label_rules[tag.name] = []

        # 构建子标签映射
        child_tags = [t for t in tags if t.level == 2]
        for child in child_tags:
            parent = next((t for t in tags if t.id == child.parent_id), None)
            if parent and parent.name in label_rules:
                label_rules[parent.name].append(child.name)

        return label_rules

    except Exception as e:
        logging.error(f"加载标签字典失败: {str(e)}")
        raise